package cv.gzd.robot.controller;

import cv.gzd.common.utils.Page;
import cv.gzd.robot.pojo.Statelog;
import cv.gzd.robot.pojo.vo.LogQueryVo;
import cv.gzd.robot.service.StateLogService;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**日志状态控制器
 * @author Jun
 */
@Controller
public class StateLogController {
    @Autowired
    StateLogService stateLogService;

    /**
     * 显示日志列表
     * @param model
     * @param logVo
     * @return
     */
    @RequestMapping("/log/list")
    public String logList(Model model, LogQueryVo logVo){
        Page<Statelog> page= stateLogService.selectPageByDevQueryVo(logVo);
        model.addAttribute("page",page);
        model.addAttribute("robotname", logVo.getRobotname());
        model.addAttribute("starttime",logVo.getStarttime());
        model.addAttribute("endtime",logVo.getEndtime());

        return "StateLog";
    }

    /**
     * 日志导出成Excel
     * @param request
     * @param response
     * @param logVo
     * @throws IOException
     */
    @RequestMapping(value = "/ExcelOut", method = RequestMethod.GET)
    @ResponseBody
    public void ExcelOut(HttpServletRequest request, HttpServletResponse response,LogQueryVo logVo) throws IOException {
        // 创建一个文件
        String path = this.getStringDate() + "~" + "Log" + ".xlsx";//创建文件名，使用的是日期加’_’加用户名+后缀名，如果使用此处要改
        System.out.println(path);

        List<Statelog> lists = stateLogService.selectLogList(logVo);
        String[] title = { "序号","时间","机器人型号", "电量","速度" };//设置EXCEL的第一行的标题头（改）
        // 创建excel工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 创建一个工作表sheet
        XSSFSheet sheet = workbook.createSheet();
        // 创建第一行
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell = null;

        // 插入第一行数据 id 地区名称
        for (int i = 0; i < title.length; i++) {
            // 创建一行的一格
            cell = row.createCell(i);
            // 赋值
            cell.setCellValue(title[i]);
        }
        // 追加数据行数
        int j = 1;
        HashMap<String, Object> list = null;
        for (int i = 0; i < lists.size(); i++) {
            // 从集合中得到一个对象
            Statelog statelog = lists.get(i);
            // 创建第下一行
            XSSFRow nextrow = sheet.createRow(i+1);
            // 创建第1列并赋值
            XSSFCell cessk = nextrow.createCell(0);
            cessk.setCellValue(statelog.getSid());

            cessk = nextrow.createCell(1);
            cessk.setCellValue(formatDatetime(statelog.getLogtime()));

            cessk = nextrow.createCell(2);
            cessk.setCellValue(statelog.getRobotname());

            cessk = nextrow.createCell(3);
            cessk.setCellValue(statelog.getPower());

            cessk = nextrow.createCell(4);
            cessk.setCellValue(statelog.getSpeed());
            //可自己再按照需要添加函数，注意将cessk = nextrow.createCell(num);这其中的num修改就行，按照顺序加上1就行
            j++;
        }
        if (path.equals("")) {
            response.getWriter().write("失败，失败原因：参数为空！");
            return;
        }
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename="+path);
        OutputStream ouputStream;
        try {
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        } catch (IOException e) {
        }
    }

    private String getStringDate() {
        Date datetime=new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd~HH-mm-ss");
        return format.format(datetime);
    }
    private String formatDatetime(Date date){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }
}
